
package com.tianbo.elfii.client.common;

import java.io.*;
import java.sql.* ;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

import com.tianbo.elfii.client.common.ElfiiCommonConfigNetWifi.ApPanel;
import com.tianbo.elfii.client.common.ElfiiCommonUtil.FeedBackType;

/**  <pre>
     <b>类功能描述：</b><pre>
     完成 开机Welcome 功能要求。
     </pre>
     @version 1.0.1
     @author 高伟 
*/

public class ElfiiCommonWelcome  { 

    public static void main(String[] args) {
    	
        final JFrame mainFrame=new ElfiiFrame();
        mainFrame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);  
                }
            }
            ) ;

        mainFrame.setSize(1024,768); 
        Dimension size=Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth=size.width;
        int screenHeight=size.height;

        mainFrame.setLocation(0,0);

        mainFrame.getContentPane().setLayout(new BorderLayout());
        mainFrame.setUndecorated(true);		  

        for (int i=0; i<args.length; i++){
            if (args[i].toLowerCase().startsWith("-upload"))
                ElfiiCommonConfigUtil.uploadMark=true;
            if (args[i].toLowerCase().startsWith("-download"))
            	ElfiiCommonConfigUtil.downloadMark=true;
        }

        ElfiiCommonWelcome gameWelcome = new ElfiiCommonWelcome(); 
        
        //start to update(replace the new files and execute the database update)
        UpdateThread updateThread = gameWelcome.new UpdateThread();
        updateThread.start();
        
        gameWelcome.setMainFrame(mainFrame);
        mainFrame.getContentPane().add(gameWelcome.createViewPanel(),BorderLayout.CENTER); //-codeing=gbk
        
        gameWelcome.initRunInfo();
        mainFrame.setVisible(true);
        
        ElfiiCommonUtil.initFeedbackAudio();
		ElfiiCommonConfigUtil.init(ElfiiCommonRunInfo.getRunInfo());
		
		if(!ElfiiCommonConfigUtil.isValid){
			
			Timer timer = new Timer();
			
			timer.schedule(new TimerTask(){
				public void run() {
					// TODO Auto-generated method stub
					InvalidTipPane invalidTipPane = new InvalidTipPane();
					invalidTipPane.screenshot();
					mainFrame.setContentPane(invalidTipPane);
					mainFrame.validate();
				}
			}, 5000);
			
			return;
		}
			

        gameWelcome.startCheckingNet();
        
        ElfiiCommonConstant.keyboard.createKeyPanel();
        ElfiiCommonConstant.keyboard.createInfoPanel();

    }

    String headline="登录/注册";    

    JButton loginButton;
    JButton historyButton;
    JButton aboutButton;
    JButton configButton;

    JFrame mainFrame;

    ElfiiCommonRunInfo runInfo;

    public void setMainFrame(JFrame mainFrame){
        this.mainFrame=mainFrame;
    }

    public void setRunInfo(ElfiiCommonRunInfo runInfo){
        this.runInfo=runInfo;
        this.mainFrame=runInfo.getMainFrame();
        
        ElfiiCommonConfigUtil.isNoNetPop = true;
    }

    public void initRunInfo(){
    	
        runInfo=ElfiiCommonRunInfo.getRunInfo();
        runInfo.initJdbc();
        runInfo.setMainFrame(mainFrame);

        if (runInfo.isRunAsTopWindow()){
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Rectangle bounds = new Rectangle(screenSize);
            mainFrame.setBounds(bounds);
            mainFrame.setAlwaysOnTop(true);
        }
    }

    public void startCheckingNet(){
    	CheckingNetThread checkingNetThread = new CheckingNetThread();
    	checkingNetThread.start();
    }

    public JPanel createWelcomePanel(){

        loginButton=new JButton();
        ImageIcon loginIcon = new ImageIcon("resource-common/images/icon/login.png");
        loginButton.setBackground(Color.black);
        loginButton.setBorderPainted(false);
        loginButton.setFocusPainted(false);
        loginButton.setIcon(loginIcon);
        loginButton.setModel(new DefaultButtonModel() {
                public boolean isPressed(){
                    return false; 
                }
            }
            ) ;
        loginButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dealLoginButton();
                    
                    ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                }
            });

        historyButton=new JButton();
        ImageIcon historyIcon = new ImageIcon("resource-common/images/icon/history.png");
        historyButton.setBackground(Color.black);
        historyButton.setBorderPainted(false);
        historyButton.setFocusPainted(false);
        historyButton.setIcon(historyIcon);
        historyButton.setModel(new DefaultButtonModel() {
                public boolean isPressed(){
                    return false; 
                }
            }
            ) ;

        historyButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dealHistoryButton();
                    ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                }
            });

        aboutButton=new JButton();
        ImageIcon aboutIcon = new ImageIcon("resource-common/images/icon/info.png");
        aboutButton.setBackground(Color.black);
        aboutButton.setBorderPainted(false);
        aboutButton.setFocusPainted(false);
        aboutButton.setIcon(aboutIcon);
        aboutButton.setModel(new DefaultButtonModel() {
                public boolean isPressed(){
                    return false; 
                }
            }
            ) ;
        aboutButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dealAboutButton();
                    ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                }
            });

        configButton=new JButton();
        ImageIcon configIcon = new ImageIcon("resource-common/images/icon/settings.png");
        configButton.setBackground(Color.black);
        configButton.setBorderPainted(false);
        configButton.setFocusPainted(false);
        configButton.setIcon(configIcon);
        configButton.setModel(new DefaultButtonModel() {
                public boolean isPressed(){
                    return false; 
                }
            }
            ) ;
        configButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dealConfigButton();
                    ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                }
            });


        JPanel selectPanel=new JPanel();
        selectPanel.setLayout(null);
        selectPanel.setBackground(Color.black);

        selectPanel.add(loginButton);
        loginButton.setBounds(300,80,160,180);

        selectPanel.add(historyButton);
        historyButton.setBounds(570,80,160,180);
        selectPanel.add(aboutButton);
        aboutButton.setBounds(300,310,160,180);
        selectPanel.add(configButton);
        configButton.setBounds(570,310,160,180);

        return selectPanel;
    }

    public JPanel createViewPanel(){
        createWelcomePanel();
        JPanel p = new JPanel(new BorderLayout()) ;
        JPanel topPanel=ElfiiCommonUtil.createTopPanelBlank(headline);
        JPanel bottomPanel=ElfiiCommonUtil.createBottomPanelBlank();
        p.setLayout(null);
        p.setBackground(Color.black);
        p.add(topPanel);
        topPanel.setBounds(0,0,1024,100);
        p.add(bottomPanel);
        bottomPanel.setBounds(0,668,1024,100);
        JPanel selectPanel=createWelcomePanel() ;
        selectPanel.setBackground(Color.black);
        p.add(selectPanel);
        selectPanel.setBounds(0,110,1024,537);
        return p;
    }

    public void dealLoginButton(){
        /* ====keep
        mainFrame.getContentPane().removeAll();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        ElfiiCommonLogin login = new ElfiiCommonLogin();
        login.setRunInfo(runInfo);
        mainFrame.getContentPane().add(login.createViewPanel(),BorderLayout.CENTER);
        mainFrame.validate();
        */

        mainFrame.getContentPane().removeAll();
        mainFrame.getContentPane().setLayout(null);
        ElfiiCommonLogin login = new ElfiiCommonLogin();
        login.setRunInfo(runInfo);
        JPanel p=login.createViewPanel();
        mainFrame.getContentPane().add(p);
        p.setBounds(0,0,1024,768);
        mainFrame.validate();
    }

    public void dealHistoryButton(){
        mainFrame.getContentPane().removeAll();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        ElfiiCommonHistorySum history = new ElfiiCommonHistorySum();
        history.setRunInfo(runInfo);
        history.clearPreSlide();
        mainFrame.getContentPane().add(history.createViewPanel(),BorderLayout.CENTER);
        mainFrame.validate();
    }
    public void dealAboutButton(){
        com.tianbo.elfii.client.customwindow.AllTrainningItemBaseWindowWithButton oneAboutELFIISystemWindow=null;
        oneAboutELFIISystemWindow = new com.tianbo.elfii.client.systemconfig.AboutELFIISystemWindow();
        oneAboutELFIISystemWindow.showThisWindowOnlyWithGoBackButton();
    }
    public void dealConfigButton(){
        mainFrame.getContentPane().removeAll();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        ElfiiCommonConfig config = new ElfiiCommonConfig();
        config.setRunInfo(runInfo);
        mainFrame.getContentPane().add(config.createViewPanel(),BorderLayout.CENTER);
        mainFrame.validate();
    }
    
    class CheckingNetThread extends Thread{
    	
    	public void run(){ 

    		int ret = ElfiiCommonConfigUtil.checkNetConnected(10,20);

    		if(ret == 0){
    			ElfiiCommonConfigUtil.startUpAndDownload();
    			return;
    		}
    		
    		if(ret == -1){
    			ElfiiCommonConfigUtil.scanSearchedWlan();
    			ElfiiCommonConfigUtil.scanSavedWlan();
    			
    			Map<String, WlanAP> searchedApList = ElfiiCommonConfigUtil.searchedApList;
    			Map<String, WlanAP> savedApList = ElfiiCommonConfigUtil.savedApList;
    			
    			Iterator iter = savedApList.entrySet().iterator();
    			
    			while(iter.hasNext()){

    				WlanAP ap = ((Map.Entry<String, WlanAP>)iter.next()).getValue();
    				System.out.println("saved AP  "+ap.getSSID());
    				if(!searchedApList.isEmpty()){
    					if(ElfiiCommonConfigUtil.searchedApList.containsKey(ap.getSSID())){
    						
    						String retStr = "";
    						int connectRet = ElfiiCommonConfigUtil.connectWlan(ap, retStr);
    						
    						if(connectRet==0){
    							boolean isConnected = false;
    							int count = 0;
    							while(true){
    								ElfiiCommonConfigUtil.lookForConnectedAp();
    								
    								if(ElfiiCommonConfigUtil.curConnectedAp!=null){
    									isConnected = true;
    									break;
    								}
    								
    								try {
    									Thread.sleep(500);
    								} catch (InterruptedException e) {
    									// TODO Auto-generated catch block
    									e.printStackTrace();
    								}
    								
    								count+=500;
    								
    								if(count>60000){
    									break;
    								}
    							}
    							
    							if(!isConnected){
    								ElfiiCommonConfigUtil.disConnectWlan();
    								break;
    							}
    							
    							ret = ElfiiCommonConfigUtil.checkNetConnected(10,10);
    							
    							if(ret==0){
    								ElfiiCommonConfigUtil.startUpAndDownload();
    								return;
    							}
    							else{
    								break;
    							}
    						}
    					}
    				}

    			}
    			
    		}
    		
			try {
				Thread.currentThread().sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 
    		while(true){
    			
    			try {
					Thread.currentThread().sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    			if(ElfiiCommonConfigUtil.isNoNetPop){
    				
    				NonetTipPane nonetTipPane = new NonetTipPane(ret);
    				nonetTipPane.screenshot();
    				nonetTipPane.contentPane = mainFrame.getContentPane();
    				mainFrame.setContentPane(nonetTipPane);
    				mainFrame.validate();
    				
    				break;
    			}
    		}
    	}
    }
    
    class UpdateThread extends Thread{
    	public UpdateThread(){
    		  
    	}
    	
    	public void run(){
    		System.out.println("--开始更新");
    		com.base.Download.executeUpdate();
    		System.out.println("--更新结束");
    	}
    }


}
